﻿using System;
using System.Windows.Forms;
using Useful.GUI;

namespace Useful
{
    public class SearchedComboBox2 : ComboBox
    {
        public class GetLisEventArgs : EventArgs
        {
            public string Text { get; private set; }
            public object DataList { get; set; }
            public int DataCount { get; set; }

            public GetLisEventArgs(string str)
            {
                Text = str;
            }
        }

        public event EventHandler<GetLisEventArgs> GetLisEvent = delegate { };

        protected override void OnTextUpdate(EventArgs e)
        {
            base.OnTextUpdate(e);

            ProcessTextUpdated();
        }

        private void ProcessTextUpdated()
        {
            GuiHelper.ProcessAction("SearchedComboBox2_TextUpdate", () =>
            {
                if (GetLisEvent != null && this.DataSource is BindingSource)
                {
                    string text = this.Text.Trim();
                    string str = text.ToUpper();

                    int oldSelectionStart = this.SelectionStart;

                    GetLisEventArgs ea = new GetLisEventArgs(str != String.Empty ? str : null);
                    GetLisEvent(this, ea);

                    // Что бы не было ошибки
                    this.DroppedDown = false;
                    this.DroppedDown = ea.DataCount > 0;

                    ((BindingSource)this.DataSource).DataSource = ea.DataList;

                    // Что бы подобрать нирину выпадающего окна
                    this.DroppedDown = false;
                    this.DroppedDown = ea.DataCount > 0;

                    this.Text = text;
                    this.SelectionLength = 0;
                    this.SelectionStart = oldSelectionStart;

                    this.Cursor = this.DefaultCursor;
                }
            },
            (msg, ex) =>
            {
                MessageBoxHelper.ShowError(ex);
            }
            );
        }
    }
}
